package com.yty.controller;

import com.yty.Utils.AliyunOSSOperator;
import com.yty.annotation.LogOperation;
import com.yty.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

/*
@PostMapping
    public Result upload(MultipartFile file)
    {
        String path = "";
        try {
            log.info("上传的文件:{}", file.getOriginalFilename());
            LocalDateTime now = LocalDateTime.now();
            String fileName = now.getYear()+"-"+now.getMonth()+"--"
                    +UUID.randomUUID().toString()
                    +file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            log.info("保存到本地得文件名:{}", fileName);
            path = "/Users/yangtianyu/Desktop/javalearn/Springboot-Mybatis/src/main/resources/static/img/"
                    + fileName;
            log.info("保存到本地得文件路径:{}", path);
            file.transferTo(new File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(path);
    }
 */
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @LogOperation
    @PostMapping
    public Result upload(MultipartFile file)
    {
        String url = "";
        log.info("上传的文件:{}", file.getOriginalFilename());
        try {
            if (!file.isEmpty()) {
                // 生成唯一文件名
                String originalFilename = file.getOriginalFilename();
                //截取后缀
                String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
                log.info("上传的文件后缀:{}", extName);
                String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
                // 上传文件
                 url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
                return Result.success(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(url);
    }

}
